package com.gtw.modules.api.controller;

import com.foxinmy.weixin4j.http.weixin.XmlResult;
import com.foxinmy.weixin4j.payment.WeixinPayProxy;
import com.foxinmy.weixin4j.payment.mch.MchPayRequest;
import com.foxinmy.weixin4j.payment.mch.Order;
import com.foxinmy.weixin4j.payment.mch.RefundResult;
import com.foxinmy.weixin4j.type.IdQuery;
import com.foxinmy.weixin4j.type.IdType;
import com.foxinmy.weixin4j.util.Consts;
import com.foxinmy.weixin4j.util.IOUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.xml.ListsuffixResultDeserializer;
import com.foxinmy.weixin4j.xml.XmlStream;
import com.gtw.common.annotation.AuthIgnoreApi;
import com.gtw.common.annotation.LoginUserApi;
import com.gtw.common.utils.PayStatus;
import com.gtw.common.utils.R;
import com.gtw.distribution.DistributionUtil;
import com.gtw.modules.api.service.*;
import com.gtw.modules.dao.TbActivityCommodityDao;
import com.gtw.modules.dao.TbCapitalpoolDao;
import com.gtw.modules.dao.TbDiscountDao;
import com.gtw.modules.entity.*;
import com.gtw.modules.sys.service.SysDividendRuleservice;
import com.gtw.utils.PayType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;

/**
 * 微信支付
 */
@RestController
@RequestMapping("/api/wxpay")
public class wxpayController {

    @Autowired
    private TbOrderService orderService;

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbShoppingCartServices tbShoppingCartServices;

    @Autowired
    private TbCommodityService tbCommodityService;

    @Autowired
    private TbPropertyService tbPropertyService;

    @Autowired
    private TbCommodityPropertyService tbCommodityPropertyService;

    @Autowired
    private TbActivityCommodityDao tbActivityCommodityDao;

    @Autowired
    private SysDividendRuleservice sysDividendRuleservice;

    @Autowired
    private TbCapitalpoolDao tbCapitalpoolDao;

    @Autowired
    private DistributionUtil distributionUtil;

    @Autowired
    private TbOrderService tbOrderService;

    @Autowired
    private TbDiscountDao tbDiscountDao;

    @Autowired
    private TbSalesLogService tbSalesLogService;
    @Autowired private WeixinPayProxy weixinPayProxy;
    private Logger logger= LoggerFactory.getLogger(wxpayController.class);

    /**
     * 下单
     *
     * @return
     */
    @RequestMapping("/doUnifiedOrder")
    public R doUnifiedOrder(@LoginUserApi TbUser tbUser, String orderno, HttpServletRequest request) throws Exception {

        TbOrder tbOrder = orderService.queryBybillno(orderno);
        MchPayRequest jsPayRequest = weixinPayProxy.createJSPayRequest(tbUser.getWxopenid(), "购买商品", tbOrder.getBillno(), tbOrder.getTotalfee() / 100d, "http://jss.youwenyuedu.com/liquor/api/wxpay/notify",
                getIpAddr(request), "gtw");

        return R.ok().put("data", jsPayRequest.toRequestObject());
    }


    /**
     * 获得客户端真实IP地址
     *
     * @param request
     * @return
     */
    private static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    /**
     * 回调
     *
     * @return
     */
    @AuthIgnoreApi
    @RequestMapping("/notify")
    public String notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String content = StringUtil.newStringUtf8(IOUtil.toByteArray(request.getInputStream()));
        Order order = ListsuffixResultDeserializer.deserialize(content,
                Order.class);
        logger.info("jsapi_notify_order_info:", order);
        //验证签名
        String sign = order.getSign();
        String valid_sign = weixinPayProxy.getWeixinSignature().sign(order);
        logger.info("微信签名----->sign={},vaild_sign={}", sign, valid_sign);
        if (!sign.equals(valid_sign)) {
            return XmlStream.toXML(new XmlResult(Consts.FAIL, "签名错误"));
        }
        TbOrder tbOrder = orderService.queryBybillno(order.getOutTradeNo());
            //修改订单状态
            tbOrder.setIspay(true);
            tbOrder.setPaydate(new Date());
            tbOrder.setPaytype(PayType.CT_WX.getName());
            tbOrder.setOrderstatus(PayStatus.beforedeliver.getName());
            tbOrder.setUpdatedate(new Date());
            orderService.update(tbOrder);

            //查询用户数据
            TbUser tbUser = tbUserService.queryByUid(tbOrder.getUid());
            TbUser tbUser1 = tbUserService.queryById(tbUser.getParentid());
            //查询商品信息
            JSONArray ja = JSONArray.fromObject(tbOrder.getShoppingcartid());
            System.out.println("1111111111111111111111111111111:" + ja.toString());

            for (int i = 0; i < ja.size(); i++) {
                System.out.println("2222222222222222222222222222222:" + tbUser1.getType());
                TbShoppingCart tbShoppingCart = tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
                TbCommodity tbCommodity = tbCommodityService.queryObject(tbShoppingCart.getCommodityid());
                tbCommodity.setSalesnum(tbCommodity.getSalesnum() + tbShoppingCart.getCommoditynumber());
                if (!tbUser1.getType().equals(2)) {

                    // 查询商品  减去库存
                    JSONArray ja2 = JSONArray.fromObject(tbShoppingCart.getSelected());
                    for (int k = 0; k < ja2.size(); k++) {
                        JSONObject jo = JSONObject.fromObject(ja2.get(k));
                        TbCommodityProperty tbCommodityProperty = tbCommodityPropertyService.queryCidAndPid(tbShoppingCart.getCommodityid(), Integer.parseInt(jo.getString("id")));
                        tbCommodityProperty.setPropertynum(tbCommodityProperty.getPropertynum() - tbShoppingCart.getCommoditynumber());
                        tbCommodityPropertyService.update(tbCommodityProperty);
                    }
                    //增加销量
                    tbCommodity.setSalesnum(tbCommodity.getSalesnum() + tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString())).getCommoditynumber());
                }

            }
            //判断是否是活动
            if("0".equals(tbOrder.getChannel())){
                if (tbUser1.getType().equals(2)) {
                    TbSalesLog tbSalesLog = new TbSalesLog();
                    tbSalesLog.setCreatedate(new Date());
                    tbSalesLog.setDismoney(Float.parseFloat(tbOrder.getTotalfee().toString()));
                    tbSalesLog.setMoney(tbOrder.getTotalfee());
                    tbSalesLog.setOrderno(tbOrder.getBillno());
                    tbSalesLog.setUserid(tbUser.getUserId());
                    tbSalesLog.setUsername(tbUser.getUsername());
                    tbSalesLog.setSelesuserid(tbUser1.getUserId());
                    tbSalesLogService.insert(tbSalesLog);
                    System.out.println("33333333333333333333333333333:" + tbUser1.getAgentinventory() + "-" + tbOrder.getTotalfee().intValue() + "+" + tbOrder.getFreight().intValue());
                    //减去代理库存
                    TbDiscount tbDiscount = tbDiscountDao.selectByType(1);

                    if (tbUser.getType() == 0) {
                        if (tbUser1.getAgentinventory() > (tbOrder.getTotalfee().intValue() - tbOrder.getFreight().intValue())) {
                            tbUser1.setBalance(tbUser1.getBalance() + (tbOrder.getTotalfee().intValue() - tbOrder.getFreight().intValue()));
                            tbUser1.setAgentinventory(tbUser1.getAgentinventory() - (tbOrder.getTotalfee().intValue() - tbOrder.getFreight().intValue()));
                            tbOrder.setRemark("proxy");
                            tbOrderService.update(tbOrder);
                        }
                    } else {
                        Float dis = tbOrder.getTotalfee() - tbOrder.getFreight();
                        if (tbUser1.getAgentinventory() > dis.intValue()) {
                            tbUser1.setBalance(tbUser1.getBalance() + dis.intValue());
                            //减去代理库存
                            float money = dis / (1 - Float.parseFloat(tbDiscount.getDiscount() / 100 + ""));
                            System.out.println("444444444444444444444:" + money);
                            tbUser1.setAgentinventory(tbUser1.getAgentinventory() - (int) money);
                            tbOrder.setRemark("proxy");
                            tbOrderService.update(tbOrder);
                        }
                    }

                    tbUserService.update(tbUser1);
                }

                if (!tbOrder.getRemark().equals("proxy")) {
                    //计算分销制度
                    //查询用户，判断是否是会员
                    if (distributionUtil.iftype(tbOrder)) {
                        System.out.println("分销成功！");
                    } else {
                        System.out.println("分销失败！");
                    }
                } else {
                    distributionUtil.distribution4(tbOrder);
                }

                if (!tbOrder.getRemark().equals("proxy")) {
                    //抽金
                    TbDividendRule tbDividendRule = sysDividendRuleservice.queryObject(1);//全球
                    TbDividendRule tbDividendRule2 = sysDividendRuleservice.queryObject(2);//代理
                    TbDividendRule tbDividendRule3 = sysDividendRuleservice.queryObject(5);//普通用户抽金到代理分红池
                    TbDividendRule tbDividendRule4 = sysDividendRuleservice.queryObject(6);//会员抽金到代理分红池
                    TbUser uer = tbUserService.queryByUid(tbOrder.getUid());
                    if (uer.getType() == 0) {
                        float dis = (tbOrder.getTotalfee() - tbOrder.getFreight()) * tbDividendRule.getFirstproportion();
                        TbCapitalpool tbCapitalpool = new TbCapitalpool();
                        tbCapitalpool = tbCapitalpoolDao.selectByPrimaryKey(1);
                        tbCapitalpool.setAmount(tbCapitalpool.getAmount() + dis);
                        tbCapitalpoolDao.updateByPrimaryKey(tbCapitalpool);
                        //普通用户抽金到代理分红池
                        float dis2 = (tbOrder.getTotalfee() - tbOrder.getFreight()) * tbDividendRule3.getFirstproportion();
                        TbCapitalpool tbCapitalpool2 = new TbCapitalpool();
                        tbCapitalpool2 = tbCapitalpoolDao.selectByPrimaryKey(2);
                        tbCapitalpool2.setAmount(tbCapitalpool2.getAmount() + dis2);
                        tbCapitalpoolDao.updateByPrimaryKey(tbCapitalpool2);
                    }
                    if (uer.getType() == 1) {
                        float dis = (tbOrder.getTotalfee() - tbOrder.getFreight()) * tbDividendRule.getProportion();
                        TbCapitalpool tbCapitalpool = new TbCapitalpool();
                        tbCapitalpool = tbCapitalpoolDao.selectByPrimaryKey(1);
                        tbCapitalpool.setAmount(tbCapitalpool.getAmount() + dis);
                        tbCapitalpoolDao.updateByPrimaryKey(tbCapitalpool);
                        //会员抽金到代理分红池
                        float dis2 = (tbOrder.getTotalfee() - tbOrder.getFreight()) * tbDividendRule4.getFirstproportion();
                        TbCapitalpool tbCapitalpool2 = new TbCapitalpool();
                        tbCapitalpool2 = tbCapitalpoolDao.selectByPrimaryKey(2);
                        tbCapitalpool2.setAmount(tbCapitalpool2.getAmount() + dis2);
                        tbCapitalpoolDao.updateByPrimaryKey(tbCapitalpool2);
                    } else {
                        float dis = (tbOrder.getTotalfee() - tbOrder.getFreight()) * tbDividendRule.getProportion();
                        TbCapitalpool tbCapitalpool = new TbCapitalpool();
                        tbCapitalpool = tbCapitalpoolDao.selectByPrimaryKey(1);
                        tbCapitalpool.setAmount(tbCapitalpool.getAmount() + dis);
                        tbCapitalpoolDao.updateByPrimaryKey(tbCapitalpool);
                    }
                }
                //如果用户是普通用户 判断金额大于99成为会员
                TbUser tbU = tbUserService.queryByUid(tbOrder.getUid());
                if (tbU.getType().equals(0)) {
                    if (tbOrder.getTotalfee() >= 9900 && tbU.getParentid() != null && tbU.getParentid() != 1) {
                        tbU.setType(1);
                        tbUserService.update(tbU);
                    }
                }
            }else{
                //不分销
                //不抽金
                //不分红
            }
        return XmlStream.toXML(new XmlResult(Consts.SUCCESS, ""));
    }

    /**
     * 退款
     * 已测试
     */
    @AuthIgnoreApi
    @RequestMapping("/refund")
    public R doRefund(String orderno) throws Exception {
        HashMap<String, String> data = new HashMap<String, String>();
        TbOrder tbOrder = tbOrderService.queryBybillno(orderno);
        RefundResult refundResult = weixinPayProxy.applyRefund(new IdQuery(orderno, IdType.TRADENO), tbOrder.getBillno(), tbOrder.getTotalfee() / 100d);

        return R.ok(refundResult.getReturnMsg());
    }
}
